package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;
    @Autowired
    private SpuAuditMapper spuAuditMapper;
    @Autowired
    private SpuLogMapper spuLogMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${GOODS_ADD_EXCHANGE}")
    private String GOODS_ADD_EXCHANGE;
    @Value("${GOODS_ADD_QUEUE_PAGE}")
    private String GOODS_ADD_QUEUE_PAGE;
    @Value("${GOODS_ADD_QUEUE_INDEX}")
    private String GOODS_ADD_QUEUE_INDEX;
    @Value("${GOODS_DEL_EXCHANGE}")
    private String GOODS_DEL_EXCHANGE;
    @Value("${GOODS_DEL_QUEUE_PAGE}")
    private String GOODS_DEL_QUEUE_PAGE;
    @Value("${GOODS_DEL_QUEUE_INDEX}")
    private String GOODS_DEL_QUEUE_INDEX;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     *
     * @param spu
     */
    @Transactional
    public void add(Spu spu) {
        spuMapper.insert(spu);
        //向mq发送消息
        rabbitTemplate.convertAndSend(GOODS_ADD_EXCHANGE,GOODS_ADD_QUEUE_PAGE,spu.getId());
        rabbitTemplate.convertAndSend(GOODS_ADD_EXCHANGE,GOODS_ADD_QUEUE_INDEX,spu.getId());
    }

    /**
     * 修改
     *
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Transactional
    public void delete(String id) {
        Map map=new HashMap();
        map.put("spuId",id);
        List<Sku> list = skuService.findList(map);
        for (Sku sku : list) {
            skuService.deletePriceFromRedisById(sku.getId());
        }
        spuMapper.deleteByPrimaryKey(id);
        //向mq发送消息
        rabbitTemplate.convertAndSend(GOODS_DEL_EXCHANGE,GOODS_DEL_QUEUE_PAGE,id);
        rabbitTemplate.convertAndSend(GOODS_DEL_EXCHANGE,GOODS_DEL_QUEUE_INDEX,id);
    }

    /**
     * 添加产品Spu Sku
     *
     * @param goods
     */
    @Transactional
    public void addGoods(Goods goods) {
        if (goods != null) {
            Spu spu = this.saveOrUpdateSpu(goods.getSpu());
            this.saveOrUpdateSkus(spu, goods.getSkuList());
        }
    }

    private Spu saveOrUpdateSpu(Spu spu) {
        if (StringUtils.isEmpty(spu.getId())) {
            spu.setId(idWorker.nextId() + "");//使用雪花算法设置id
            spuMapper.insert(spu);
            CategoryBrand categoryBrand = new CategoryBrand(spu.getCategory3Id() + "", spu.getBrandId() + "");
            int count = categoryBrandMapper.selectCount(categoryBrand);
            if (count == 0) {
                categoryBrandMapper.insert(categoryBrand);
            }
        } else {
            spuMapper.updateByPrimaryKeySelective(spu);//更新Spu
        }
        System.out.println(spu.getId());
        return spu;
    }

    private void saveOrUpdateSkus(Spu spu, List<Sku> skuList) {
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        Date date = new Date();
        //删除原有的sku 准备重新插入
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        skuMapper.deleteByExample(example);

        for (Sku sku : skuList) {
            String name = spu.getName();
            if (StringUtils.isEmpty(sku.getSpec())) {
                sku.setSpec("{}");
            }
            Map<String, String> map = JSON.parseObject(sku.getSpec(), Map.class);
            for (String str : map.values()) {
                name += " " + str;
            }
            sku.setName(name);
            //设置创建 更新时间
            if (StringUtils.isEmpty(sku.getId())) {
                sku.setId(idWorker.nextId() + "");
                sku.setSpuId(spu.getId());
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                //设置分类信息
                sku.setCategoryId(category.getId());
                sku.setCategoryName(category.getName());
                //设置初始评论数量 销售数量
                sku.setCommentNum(0);
                sku.setSaleNum(0);
                skuMapper.insert(sku);
            } else {
                sku.setUpdateTime(date);
                skuMapper.insertSelective(sku);
            }
            skuService.savePriceToRedisById(sku.getId(),sku.getPrice());
        }
    }

    /**
     * 根据id查询产品
     *
     * @param id
     * @return
     */
    public Goods findGoodsBySpuId(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //根据spu的id查询sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", id);
        List<Sku> skuList = skuMapper.selectByExample(example);
        //聚合为goods
        Goods goods = new Goods(spu, skuList);
        return goods;
    }

    @Transactional
    public void audit(String id, String status, String message) {
        //设置商品审核状态
        Spu spu = new Spu();
        spu.setId(id);
        if (status == "1") {
            spu.setIsMarketable("1");
        }
        spu.setStatus(status);
        spuMapper.updateByPrimaryKeySelective(spu);
        //设置审核信息
        SpuAudit spuAudit = new SpuAudit();
        spuAudit.setId(idWorker.nextId() + "");
        spuAudit.setSpuId(id);
        spuAudit.setStatus(status);
        spuAudit.setMessage(message);
        spuAudit.setDate(new Date());
        spuAuditMapper.insert(spuAudit);

    }

    @Transactional
    public void pull(String spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
        //保存日志
        SpuLog spuLog = new SpuLog();
        spuLog.setId(idWorker.nextId() + "");
        spuLog.setSpuId(spuId);
        spuLog.setDate(new Date());
        spuLog.setMessage("下架商品");
        spuLogMapper.insert(spuLog);

    }

    @Transactional
    public void put(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (!"1".equals(spu.getStatus())) {
            throw new RuntimeException("此商品未通过审核");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKey(spu);
        //记录日志
        SpuLog spuLog = new SpuLog();
        spuLog.setId(idWorker.nextId() + "");
        spuLog.setSpuId(spuId);
        spuLog.setDate(new Date());
        spuLog.setMessage("商品上架");
        spuLogMapper.insert(spuLog);

    }

    @Transactional
    public int putMany(String[] spuIds) {
        Spu spu = new Spu();
        spu.setIsMarketable("1");
        Example example = new Example(Spu.class);
        int count = 0;
        for (String spuId : spuIds) {
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id", spuId);
            criteria.andEqualTo("status", "1");
            criteria.andEqualTo("isMarketable", "0");
            int i = spuMapper.updateByExampleSelective(spu, example);
            if (i > 0) {
                SpuLog spuLog = new SpuLog();
                spuLog.setId(idWorker.nextId() + "");
                spuLog.setSpuId(spuId);
                spuLog.setDate(new Date());
                spuLog.setMessage("上架商品");
                spuLogMapper.insert(spuLog);
                count++;
            }
        }
        return count;
    }

    public void isDelete(String spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);
        //商品日志
        SpuLog spuLog = new SpuLog();
        spuLog.setId(idWorker.nextId() + "");
        spuLog.setSpuId(spuId);
        spuLog.setDate(new Date());
        spuLog.setMessage("删除商品到回收站");
        spuLogMapper.insert(spuLog);
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andLike("sn", "%" + searchMap.get("sn") + "%");
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andLike("isMarketable", "%" + searchMap.get("isMarketable") + "%");
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andLike("isEnableSpec", "%" + searchMap.get("isEnableSpec") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andLike("status", "%" + searchMap.get("status") + "%");
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
